package com.csdj.t309.controller;


import com.csdj.t309.entity.*;
import com.csdj.t309.service.UserService;
import com.csdj.t309.utils.CookiesUtils;
import com.csdj.t309.utils.RedisUtils;
import com.csdj.t309.utils.UUidUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    ObjectMapper mapper = new ObjectMapper();
    @ResponseBody
    @GetMapping("login")
    public String chaxun(HttpServletResponse response, @RequestParam(value = "zh",required = false) String zh, @RequestParam(value = "pwd",required = false) String pwd) throws JsonProcessingException {
        UserExample userExample=new UserExample();
        System.out.println(zh);
        userExample.createCriteria().andUserEqualTo(zh).andPwdEqualTo(pwd);
        User user=userService.selectByExample(userExample).get(0);
        if(user.getId()>0){
            String token= UUidUtils.suiji32();
            Jedis jedis= RedisUtils.lianjie();
            String userJson = mapper.writeValueAsString(user);
            jedis.hset("user","user"+user.getId(),userJson);
            jedis.hset("token","usertoken"+user.getId(),token);
            CookiesUtils.addCookie(response,"token",token,60*10);
            CookiesUtils.addCookie(response,"id",user.getId().toString(),60*10);
            return "true";
        }else {
            return "false";
        }
    }
    @GetMapping("error")
    public String error() throws JsonProcessingException {
       return "error";
    }
    @ResponseBody
    @GetMapping("yanzheng")
    public String yanzheng(HttpServletRequest request) throws JsonProcessingException {
        Cookie id= CookiesUtils.getCookieByName(request,"id");
        Jedis jedis=RedisUtils.lianjie();
        return jedis.hget("user","user"+id.getValue());
    }
}
